package micro_demo

import (
	"context"
	"protobuf/pb"

	"go-micro.dev/v4"
	"go-micro.dev/v4/metadata"
	"go-micro.dev/v4/server"
	"go-micro.dev/v4/util/log"
)

// Sub All methods of Sub will be executed when a message is received
type Sub struct{}

// Process Method can be of any name
func (s *Sub) Process(ctx context.Context, event *pb.BarResponse) error {
	md, _ := metadata.FromContext(ctx)

	topic, ok := md.Get("Micro-Topic")
	if ok {
		log.Infof("topic: %s", topic)
		log.Infof("event: %v", event)
	}

	// do something with event
	return nil
}

// Alternatively a function can be used
func subEv(ctx context.Context, event *pb.BarResponse) error {
	md, _ := metadata.FromContext(ctx)

	topic, ok := md.Get("Micro-Topic")
	if ok {
		log.Infof("topic: %s", topic)
		log.Infof("event: %v", event)
	}
	// do something with event
	return nil
}

// Subscribe 订阅
func Subscribe() error {
	// create a service
	service := micro.NewService(
		micro.Name("future"),
		micro.Version("latest"),
	)
	// initialise flags
	service.Init()

	// register subscriber
	// 此方式触发 sub.Process 函数
	if err := micro.RegisterSubscriber("future.1m", service.Server(), &Sub{}); err != nil {
		log.Fatal(err)
	}

	// register subscriber with queue, each msg is delivered to a unique subscriber
	// 事件到队列中, 确保不丢失
	if err := micro.RegisterSubscriber("future.5m", service.Server(), subEv, server.SubscriberQueue("queue.pubsub")); err != nil {
		log.Fatal(err)
	}

	// run service
	err := service.Run()
	return err
}
